//
//  ModelManager.swift
//  AutoModel
//
//  Created by 好米有易 on 2019/8/5.
//  Copyright © 2019 own. All rights reserved.
//

import Cocoa

class ModelManager {
    static let shared = ModelManager()
    private var finalString = ""
    private var numbers = 0;
    private var spaceString = "    "
    private init(){}
    func makeModel(name: String, data:[String : Any]) -> String {
         makeStructFile(name: name, data: data)
        return "import Foundation\n" + finalString
    }

   private func makeStructFile(name: String, data:[String : Any]) {
        var properts = [String]()
        var assignments = [String]()
        let keys = data.keys
        for key in keys {
            guard let tempValue = data[key] else { return }
            if tempValue is String {
                properts.append(makeString(property: key))
                assignments.append(spaceString + initString(property: key))
            }
            if tempValue is Int {
                properts.append(makeInt(property: key))
                assignments.append(spaceString + initInt(property:key))
            }
            if tempValue is NSNull {
                properts.append(makeNSNull(property: key))
                assignments.append(spaceString + initNSNull(property: key))
            }
            if tempValue is Array<Any> {
                properts.append(makeObjects(property: key))
                assignments.append(initObjects(property: key, spacing: spaceString))
                if let dict = (tempValue as! [Any]).first {
                    makeStructFile(name: key.capitalized, data: dict as! [String : AnyObject])
                }
            }
            if tempValue is Dictionary<String, Any> {
                properts.append(makeObject(property: key))
                assignments.append(initObject(property: key, spacing: spaceString))
                makeStructFile(name: key.capitalized, data: tempValue as! [String : Any])
            }
        }
        var property = ""
        var assignment = ""
        for index in 0...properts.count - 1 {
            property.append(properts[index])
            assignment.append(assignments[index])
        }
    let initMethodString = structInitialize(assignment: assignment)
        finalString.appendAtFrist(str: "// MARK: - \(name.capitalized)\nstruct \(name.capitalized) {\n\(property)\(initMethodString)\n}\n")
    }

}
